const swaggerJSDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const swaggerDefinition = {
  openapi: '3.0.0',
  info: {
    title: 'Express API with Swagger',
    version: '1.0.0',
  },
  servers: [
    {
      url: 'http://localhost:3000/api',
      description: 'Development server',
    },
  ],
};
const options = {
  swaggerDefinition,
  // 路径到API文档的地方
  apis: [`${__dirname}/../routes/*.js`], // e.g. assuming your routes are in a directory called "routes"
  // apis: [`${__dirname}/../routes/q.js`], // e.g. assuming your routes are in a directory called "routes"
};

const swaggerInstall = (app) => {
  // app.use(
  //   '/api-docs',
  //   swaggerUi.serve,
  //   swaggerUi.setup(swaggerJSDoc(options, { logger: console.log }))
  // );

   // 添加时间戳查询参数以避免缓存问题
   app.use('/api-docs', (req, res, next) => {
    if (req.path === '/api-docs') {
      req.url = `${req.url}?${new Date().getTime()}`;
    }
    next();
  });

  // 服务 Swagger UI 的静态文件
  app.use('/api-docs', swaggerUi.serve);

  // 设置 Swagger UI 的配置
  app.use('/api-docs', swaggerUi.setup(swaggerJSDoc(options, { logger: console.log }), {
    explorer: true, // 启用 Swagger UI 的 API 测试界面
    swaggerOptions: {
      // 以下配置用于解决缓存问题
      layout: "StandaloneLayout"
    }
  }));
  
};
module.exports=swaggerInstall
